
function iter(obj){
	var itr = obj.__iter__(obj);
	return itr;
}

function next(obj){
	var res = obj.__next__(obj);
	return res;
}

function test1(){
	/*
	def func():
		i = 0
		yield i
		
		i += 1
		yield i
		
		i += 1
		raise StopIteration

	for i in func():
		print(i)
	*/
	var func = {
		__iter__: function (self){
			return self;
		},
		__next__: function (self){
			if (self.__temps__ === undefined){
				self.__temps__ = {};
				
				self.__temps__.segs = [
					function (globals, locals){
						locals.i = 0;
						self.__temps__.idx++;
						return locals.i;
					},
					function (globals, locals){
						locals.i++;
						self.__temps__.idx++;
						return locals.i;
					},
					function (globals, locals){
						locals.i++;
						self.__temps__.idx++;
						throw StopIteration;
					}
				];
				
				self.__temps__.idx = 0;
			}
			
			return self.__temps__.segs[self.__temps__.idx](self, self);
		},
	};

	var i;
	var itr = iter(func);

	while (true){
		try {
			i = next(itr);
		} catch (e) {
			break;
		}
		
		print(i);
	}
}

function test2(){
	/*
	def func():
		i = 0
		
		while i < 10:
			if i % 2 == 0:
				yield i
			
			i += 1
		
		raise StopIteration

	for i in func():
		print(i)
	*/
	var func = {
		__iter__: function (self){
			return self;
		},
		__next__: function (self){
			if (self.__temps__ === undefined){
				var globals = {};
				var locals = self;
				self.__temps__ = {};
				
				self.__temps__.segs = [
					function (globals, locals){
						locals.i = 0;
						self.__temps__.idx++;
						return self.__temps__.segs[self.__temps__.idx](globals, locals);
					},
					function (globals, locals){
						if (locals.i < 10){
							if (locals.i % 2 === 0){
								return locals.i;
							}
						}
					},
					function (globals, locals){
						
					},
				];
				
				self.__temps__.idx = 0;
			}
			
			return self.__temps__.segs[self.__temps__.idx](globals, locals);
		},
	};

	var i;
	var itr = iter(func);

	while (true){
		try {
			i = next(itr);
		} catch (e) {
			break;
		}
		
		print(i);
	}
}

test1();
